package com.bigData.main.controller;

import cn.hutool.core.date.DateUtil;
import com.bigData.main.dto.CleaningRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.sql.Date;
import java.sql.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.bigData.main.controller.Const.*;

@RestController
@RequestMapping("/api/hdfs")
@Slf4j
public class HDFSController {
    @PostMapping("/insert-to-mysql")
    public ResponseEntity<?> insertToMySQL(@RequestBody Map<String, String> request) {
        String filePath = request.get("filePath");

        Connection conn = null;
        PreparedStatement pstmt = null;
        int insertedRows = 0;

        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path hdfsPath = new Path(filePath);

            if (!fs.exists(hdfsPath)) {
                return ResponseEntity.status(404).body("文件不存在");
            }

            List<String> lines = new ArrayList<>();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(hdfsPath), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    lines.add(line);
                }
            }

            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            conn.setAutoCommit(false);

            //ID,车名,颜色,价格,时间,状态
            String sql = "INSERT INTO car (cid,cname, color, price, storage, time, status, creator) VALUES (?,?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);

            int batchSize = 100;
            for (String line : lines) {
                Map<String, String> data = parseCarDataLine(line);
                if (data == null || data.isEmpty()) continue;

                try {
                    pstmt.setLong(1, Long.valueOf(data.get("cid")));
                    pstmt.setString(2, data.get("cname"));
                    pstmt.setString(3, data.get("color"));
                    pstmt.setLong(4, Long.parseLong(data.get("price")));
                    pstmt.setString(5, data.get("storage"));
                    pstmt.setDate(6, Date.valueOf(data.get("time")));
                    pstmt.setString(7, data.get("status"));
                    pstmt.setString(8, data.get("creator"));

                    pstmt.addBatch();
                    insertedRows++;

                    if (insertedRows % batchSize == 0) {
                        pstmt.executeBatch();
                    }
                } catch (Exception e) {
                    System.err.println("插入数据出错: " + line + ", 错误: " + e.getMessage());
                }
            }

            pstmt.executeBatch();
            conn.commit();

            return ResponseEntity.ok("成功插入 " + insertedRows + " 条记录到MySQL数据库");
        } catch (Exception e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            return ResponseEntity.status(500).body("插入MySQL失败: " + e.getMessage());
        } finally {
            try {
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private Map<String, String> parseCarDataLine(String line) {
        Map<String, String> data = new HashMap<>();
        try {
            String[] parts = line.split(",\\s*");
            for (String part : parts) {
                String[] kv = part.split(":\\s*", 2);
                if (kv.length != 2) continue;

                String key = kv[0].trim();
                String value = kv[1].trim();

                switch (key) {
                    case "ID":
                        data.put("cid", value);
                        break;
                    case "车名":
                        data.put("cname", value);
                        break;
                    case "颜色":
                        data.put("color", value);
                        break;
                    case "价格":
                        data.put("price", value);
                        break;
                    case "存储地点":
                        data.put("storage", value);
                        break;
                    case "时间":
                        data.put("time", value);
                        break;
                    case "状态":
                        data.put("status", value);
                        break;
                    case "创建人":
                        data.put("creator", value);
                        break;
                }
            }
        } catch (Exception e) {
            System.err.println("解析行出错: " + line);
        }
        return data;
    }

    @PostMapping("/clean")
    public ResponseEntity<?> cleanData(@RequestBody CleaningRequest request) {
        String filePath = request.getFilePath();
        boolean deduplication = request.isDeduplication();
        boolean wordFrequency = request.isWordFrequency();

        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path fileToClean = new Path(filePath);

            if (!fs.exists(fileToClean)) {
                return ResponseEntity.status(404).body("文件不存在");
            }

            List<String> lines = new ArrayList<>();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(fileToClean), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    lines.add(line);
                }
            }

            Map<String, Integer> carNameTotalQuantity = new HashMap<>();
            Map<String, Integer> colorTotalQuantity = new HashMap<>();
            Map<String, Integer> storageTotalQuantity = new HashMap<>();
            Map<String, Integer> statusTotalQuantity = new HashMap<>();

            if (wordFrequency) {
                for (String line : lines) {
                    Map<String, String> data = parseCarDataLine(line);
                    if (data == null || data.isEmpty()) continue;

                    String cname = data.get("cname");
                    String color = data.get("color");
                    String storage = data.get("storage");
                    String status = data.get("status");

                    // 统计车名词频
                    if (cname != null && !cname.isEmpty()) {
                        carNameTotalQuantity.put(cname, carNameTotalQuantity.getOrDefault(cname, 0) + 1);
                    }

                    // 统计颜色词频
                    if (color != null && !color.isEmpty()) {
                        colorTotalQuantity.put(color, colorTotalQuantity.getOrDefault(color, 0) + 1);
                    }

                    // 统计存储地点词频
                    if (storage != null && !storage.isEmpty()) {
                        storageTotalQuantity.put(storage, storageTotalQuantity.getOrDefault(storage, 0) + 1);
                    }

                    // 统计状态词频
                    if (status != null && !status.isEmpty()) {
                        statusTotalQuantity.put(status, statusTotalQuantity.getOrDefault(status, 0) + 1);
                    }
                }
            }

            // 获取 uid，用于动态生成目录路径
            String uid = request.getUid(); // 假设 CleaningRequest 中包含 uid
            uid = uid != null ? uid : "1"; // 默认值为 "1"

            if (deduplication) {
                log.info("开始  去重处理：{}", DateUtil.now());
                String deduplicationFileName = System.currentTimeMillis() + "_deduplication_" + fileToClean.getName();
                Path deduplicationPath = new Path(getHC2Dir(uid), deduplicationFileName); // 使用动态路径
                try (FSDataOutputStream out = fs.create(deduplicationPath)) {
                    for (String line : lines) {
                        out.write((line + "\n").getBytes());
                    }
                }
                log.info("结束  去重处理：{}", DateUtil.now());
            }

            if (wordFrequency) {
                log.info("开始  词频统计：{}", DateUtil.now());
                String wordFrequencyFileName = System.currentTimeMillis() + "_wordFrequency_" + fileToClean.getName();
                Path wordFrequencyPath = new Path(getHC3Dir(uid), wordFrequencyFileName); // 使用动态路径
                try (FSDataOutputStream out = fs.create(wordFrequencyPath)) {
                    // 写入车名词频
                    out.write("车名词频统计:\n".getBytes());
                    carNameTotalQuantity.forEach((key, value) -> {
                        try {
                            out.write((key + ": " + value + "\n").getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });

                    // 写入颜色词频
                    out.write("\n颜色词频统计:\n".getBytes());
                    colorTotalQuantity.forEach((key, value) -> {
                        try {
                            out.write((key + ": " + value + "\n").getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });

                    // 写入存储地点词频
                    out.write("\n存储地点词频统计:\n".getBytes());
                    storageTotalQuantity.forEach((key, value) -> {
                        try {
                            out.write((key + ": " + value + "\n").getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });

                    // 写入状态词频
                    out.write("\n状态词频统计:\n".getBytes());
                    statusTotalQuantity.forEach((key, value) -> {
                        try {
                            out.write((key + ": " + value + "\n").getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                }
                log.info("结束  词频统计：{}", DateUtil.now());
            }

            return ResponseEntity.ok("数据清洗成功");
        } catch (IOException e) {
            return ResponseEntity.status(500).body("数据清洗失败: " + e.getMessage());
        }
    }

    /**
     * 将 词频统计结果插入  mysql数据库
     *
     * @param request
     * @return
     */
    @PostMapping("/insert-word-frequency-to-mysql")
    public ResponseEntity<?> insertWordFrequencyToMySQL(@RequestBody Map<String, String> request) {
        String filePath = request.get("filePath");
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path hdfsPath = new Path(filePath);
            List<String> lines = readHDFSFile(fs, hdfsPath);

            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            conn.setAutoCommit(false);

            Map<String, Integer> carNameTotalQuantity = new HashMap<>();
            Map<String, Integer> colorTotalQuantity = new HashMap<>();
            Map<String, Integer> storageTotalQuantity = new HashMap<>();
            Map<String, Integer> statusTotalQuantity = new HashMap<>();

            Pattern pattern = Pattern.compile("^(.*?):\\s*(\\d+)$");
            String currentCategory = null;

            for (String line : lines) {
                if (line.contains("车名词频统计:")) {
                    currentCategory = "carName";
                    continue;
                } else if (line.contains("颜色词频统计:")) {
                    currentCategory = "color";
                    continue;
                } else if (line.contains("存储地点词频统计:")) {
                    currentCategory = "storage";
                    continue;
                } else if (line.contains("状态词频统计:")) {
                    currentCategory = "status";
                    continue;
                }

                if (currentCategory == null) continue;

                Matcher matcher = pattern.matcher(line);
                if (!matcher.matches()) {
                    System.err.println("无效的统计格式，数据内容为: " + line);
                    continue;
                }

                String key = matcher.group(1).trim();
                int value = Integer.parseInt(matcher.group(2).trim());

                switch (currentCategory) {
                    case "carName":
                        carNameTotalQuantity.put(key, value);
                        break;
                    case "color":
                        colorTotalQuantity.put(key, value);
                        break;
                    case "storage":
                        storageTotalQuantity.put(key, value);
                        break;
                    case "status":
                        statusTotalQuantity.put(key, value);
                        break;
                }
            }

            String sql = "INSERT INTO car_statistics (id,car_name, color, storage, status, total_quantity) VALUES (?,?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);

            // 插入车名词频
            for (Map.Entry<String, Integer> entry : carNameTotalQuantity.entrySet()) {
                pstmt.setLong(1, System.nanoTime());
                pstmt.setString(2, entry.getKey());
                pstmt.setNull(3, java.sql.Types.VARCHAR);
                pstmt.setNull(4, java.sql.Types.VARCHAR);
                pstmt.setNull(5, java.sql.Types.VARCHAR);//status

                pstmt.setInt(6, entry.getValue());
                pstmt.addBatch();
            }

            // 插入颜色词频
            for (Map.Entry<String, Integer> entry : colorTotalQuantity.entrySet()) {
                pstmt.setLong(1, System.nanoTime());
                pstmt.setNull(2, java.sql.Types.VARCHAR);
                pstmt.setString(3, entry.getKey());
                pstmt.setNull(4, java.sql.Types.VARCHAR);
                pstmt.setNull(5, java.sql.Types.VARCHAR);//status
                pstmt.setInt(6, entry.getValue());
                pstmt.addBatch();
            }

            // 插入存储地点词频
            for (Map.Entry<String, Integer> entry : storageTotalQuantity.entrySet()) {
                pstmt.setLong(1, System.nanoTime());
                pstmt.setNull(2, java.sql.Types.VARCHAR);
                pstmt.setNull(3, java.sql.Types.VARCHAR);
                pstmt.setString(4, entry.getKey());
                pstmt.setNull(5, java.sql.Types.VARCHAR);//status
                pstmt.setInt(6, entry.getValue());
                pstmt.addBatch();
            }

            // 插入状态词频
            for (Map.Entry<String, Integer> entry : statusTotalQuantity.entrySet()) {
                pstmt.setLong(1, System.nanoTime());
                pstmt.setNull(2, java.sql.Types.VARCHAR);
                pstmt.setNull(3, java.sql.Types.VARCHAR);
                pstmt.setNull(4, java.sql.Types.VARCHAR);
                pstmt.setString(5, entry.getKey());
                pstmt.setInt(6, entry.getValue());
                pstmt.addBatch();
            }

            pstmt.executeBatch();
            conn.commit();
            return ResponseEntity.ok("成功插入统计结果，共插入 " +
                    (carNameTotalQuantity.size() + colorTotalQuantity.size() + storageTotalQuantity.size() + statusTotalQuantity.size()) + " 条记录");
        } catch (Exception e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
            }
            return ResponseEntity.status(500).body("插入失败: " + e.getMessage());
        } finally {
            try {
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
            }
        }
    }

    private List<String> readHDFSFile(FileSystem fs, Path path) throws IOException {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(path), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }
        return lines;
    }

    /**
     * 获取去重历史
     *
     * @param limit
     * @param uid
     * @return
     */
    @GetMapping("/deduplication-history")
    public ResponseEntity<?> getDeduplicationHistory(@RequestParam int limit, @RequestParam String uid) {
        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path hc2Path = new Path(getHC2Dir(uid)); // 根据 uid 动态生成目录路径

            if (!fs.exists(hc2Path)) {
                return ResponseEntity.ok(Collections.emptyList());
            }

            FileStatus[] statuses = fs.listStatus(hc2Path);
            List<Map<String, Object>> history = new ArrayList<>();

            for (FileStatus status : statuses) {
                if (status.isFile()) {
                    Map<String, Object> file = new HashMap<>();
                    file.put("name", status.getPath().getName());
                    file.put("path", status.getPath().toString());
                    file.put("uploadTime", status.getModificationTime());
                    history.add(file);
                }
            }

            history.sort((a, b) -> Long.compare((Long) b.get("uploadTime"), (Long) a.get("uploadTime")));

            int endIndex = Math.min(limit, history.size());
            return ResponseEntity.ok(history.subList(0, endIndex));
        } catch (IOException e) {
            return ResponseEntity.status(500).body("获取去重历史失败: " + e.getMessage());
        }
    }

    /**
     * 获取词频统计历史
     *
     * @param limit
     * @param uid
     * @return
     */
    @GetMapping("/word-frequency-history")
    public ResponseEntity<?> getWordFrequencyHistory(@RequestParam int limit, @RequestParam String uid) {
        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path hc3Path = new Path(getHC3Dir(uid)); // 根据 uid 动态生成目录路径

            if (!fs.exists(hc3Path)) {
                return ResponseEntity.ok(Collections.emptyList());
            }

            FileStatus[] statuses = fs.listStatus(hc3Path);
            List<Map<String, Object>> history = new ArrayList<>();

            for (FileStatus status : statuses) {
                if (status.isFile()) {
                    Map<String, Object> file = new HashMap<>();
                    file.put("name", status.getPath().getName());
                    file.put("path", status.getPath().toString());
                    file.put("uploadTime", status.getModificationTime());
                    history.add(file);
                }
            }

            history.sort((a, b) -> Long.compare((Long) b.get("uploadTime"), (Long) a.get("uploadTime")));

            int endIndex = Math.min(limit, history.size());
            return ResponseEntity.ok(history.subList(0, endIndex));
        } catch (IOException e) {
            return ResponseEntity.status(500).body("获取词频统计历史失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件列表
     *
     * @param limit
     * @param uid
     * @return
     */
    @GetMapping("/files")
    public ResponseEntity<?> getFiles(@RequestParam int limit, @RequestParam String uid) {
        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path hcPath = new Path(getHCDir(uid)); // 根据 uid 动态生成目录路径

            if (!fs.exists(hcPath)) {
                return ResponseEntity.ok(Collections.emptyList());
            }

            FileStatus[] statuses = fs.listStatus(hcPath);
            List<Map<String, Object>> files = new ArrayList<>();

            for (FileStatus status : statuses) {
                if (status.isFile()) {
                    Map<String, Object> file = new HashMap<>();
                    file.put("name", status.getPath().getName());
                    file.put("path", status.getPath().toString());
                    file.put("uploadTime", status.getModificationTime());
                    files.add(file);
                }
            }

            files.sort((a, b) -> Long.compare((Long) b.get("uploadTime"), (Long) a.get("uploadTime")));

            int endIndex = Math.min(limit, files.size());
            return ResponseEntity.ok(files.subList(0, endIndex));
        } catch (IOException e) {
            return ResponseEntity.status(500).body("获取文件失败: " + e.getMessage());
        }
    }

    @GetMapping("/preview")
    public ResponseEntity<?> previewFile(@RequestParam String path) {
        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path filePath = new Path(path);

            if (!fs.exists(filePath)) {
                return ResponseEntity.status(404).body("文件不存在");
            }

            FSDataInputStream inputStream = fs.open(filePath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder content = new StringBuilder();

            String line;
            int maxContentLength = 10000;
            int currentLength = 0;

            while ((line = reader.readLine()) != null && currentLength < maxContentLength) {
                content.append(line).append("\n");
                currentLength += line.length() + 1;
            }

            reader.close();
            return ResponseEntity.ok()
                    .header("Content-Type", "text/plain; charset=UTF-8")
                    .body(content.toString());
        } catch (IOException e) {
            return ResponseEntity.status(500).body("预览文件失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    public ResponseEntity<?> deleteFile(@RequestParam String path) {
        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path filePath = new Path(path);

            if (!fs.exists(filePath)) {
                return ResponseEntity.status(404).body("文件不存在");
            }

            fs.delete(filePath, false);
            return ResponseEntity.ok("文件已删除");
        } catch (IOException e) {
            return ResponseEntity.status(500).body("删除文件失败: " + e.getMessage());
        }
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam String path) {
        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path filePath = new Path(path);

            if (!fs.exists(filePath)) {
                return ResponseEntity.status(404).body(null);
            }

            FSDataInputStream inputStream = fs.open(filePath);
            byte[] fileContent = new byte[(int) fs.getFileStatus(filePath).getLen()];
            inputStream.readFully(fileContent);
            inputStream.close();

            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + filePath.getName() + "\"")
                    .body(fileContent);
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 云端文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件为空");
            return ResponseEntity.status(400).body(error);
        }

        try {
            // 创建暂存目录
            File tempDir = new File(TEMP_UPLOAD_DIR);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }

            // 保存文件到暂存目录
            String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            File tempFile = new File(tempDir, filename);
            file.transferTo(tempFile);

            Map<String, String> response = new HashMap<>();
            response.put("status", "temp_success");
            response.put("message", "文件已暂存");
            response.put("tempPath", tempFile.getAbsolutePath());
            log.info("云端文件上传存储目录：{}", tempFile.getAbsolutePath());

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 上传车辆数据文件 所有车辆数据 (5).txt
     *
     * @param file
     * @param uid
     * @return
     */
    @PostMapping("/uploads")
    public ResponseEntity<?> uploadsFile(@RequestParam("file") MultipartFile file, @RequestParam String uid) {
        if (file == null || file.isEmpty()) {
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件为空");
            return ResponseEntity.status(400).body(error);
        }

        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path hcPath = new Path(getHCDir(uid)); // 使用动态路径

            if (!fs.exists(hcPath)) {
                fs.mkdirs(hcPath);
            }

            String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            Path filePath = new Path(hcPath, filename);

            FSDataOutputStream outputStream = fs.create(filePath, true);
            outputStream.write(file.getBytes());
            outputStream.close();

            Map<String, String> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "文件上传成功");
            response.put("path", filePath.toString());

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 接收云端文件
     *
     * @param request
     * @return
     */
    @PostMapping("/receive")
    public ResponseEntity<?> receiveExternalFile(@RequestBody Map<String, String> request) {
        String code = request.get("code");
        if (!"123456".equals(code)) {
            return ResponseEntity.status(403).body("对接码不正确");
        }

        String tempPath = request.get("tempPath");
        if (tempPath == null || tempPath.isEmpty()) {
            return ResponseEntity.status(400).body("暂存路径无效");
        }

        String uid = request.get("uid"); // 从请求中获取 uid
        uid = uid != null ? uid : "1"; // 默认值为 "1"

        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            return ResponseEntity.status(404).body("暂存文件不存在");
        }

        try {
            // 上传到HDFS
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path hcPath = new Path(getHCDir(uid)); // 使用动态路径

            if (!fs.exists(hcPath)) {
                fs.mkdirs(hcPath);
            }

            String filename = System.currentTimeMillis() + "_" + tempFile.getName();
            Path hdfsPath = new Path(hcPath, filename);

            FSDataOutputStream outputStream = fs.create(hdfsPath, true);
            outputStream.write(Files.readAllBytes(tempFile.toPath()));
            outputStream.close();

            // 保存到本地目录
            File localDir = new File(LOCAL_DOWNLOAD_DIR);
            if (!localDir.exists()) {
                localDir.mkdirs();
            }
            File localFile = new File(localDir, filename);
            Files.copy(tempFile.toPath(), localFile.toPath());
            log.info("接收到的云上传文件存储到本地的路径为：{}", localFile.getAbsolutePath());

            // 删除暂存文件
            tempFile.delete();

            Map<String, String> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "文件已上传到HDFS和本地目录");
            response.put("hdfsPath", hdfsPath.toString());
            response.put("localPath", localFile.getAbsolutePath());

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件处理失败: " + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    @GetMapping("/file-detail")
    public ResponseEntity<?> getFileDetail(@RequestParam String path) {
        try {
            Configuration config = getHDFSConfig();
            FileSystem fs = FileSystem.get(config);
            Path filePath = new Path(path);

            if (!fs.exists(filePath)) {
                return ResponseEntity.status(404).body("文件不存在");
            }

            FileStatus fileStatus = fs.getFileStatus(filePath);
            Map<String, Object> detail = new HashMap<>();
            detail.put("name", fileStatus.getPath().getName());
            detail.put("path", fileStatus.getPath().toString());
            detail.put("uploadTime", fileStatus.getModificationTime());
            detail.put("size", fileStatus.getLen());

            return ResponseEntity.ok(detail);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("获取文件详细信息失败: " + e.getMessage());
        }
    }
}
